import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/config/app_data_cache.dart';
import 'package:app/src/manager/ywx_manager.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/http/bean/ywx_limit.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/utils/image_path_utils.dart';

///背景色
Color backgroundColor() {
  return AppColors.backgroundColorWithWhite;
}

///首页搜索
class SearchRoute extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<SearchRoute> {
  _Presenter presenter = _Presenter();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    px.init(context);
    var scaffold = Scaffold(
      backgroundColor: backgroundColor(),
      appBar: AppBar(
        //fixme 搜索框位置
        backgroundColor: backgroundColor(),
        elevation: 0,
        leading: AppUi.getBack(context, () {
          return false;
        }),
        leadingWidth: 33,
        titleSpacing: 0,
        title: _search(context),
      ),
      body: Material(color: backgroundColor(), child: _body(context)),
    );
    var willPopScope = WillPopScope(
      child: scaffold,
      onWillPop: () async {
        return true; //true 不屏蔽返回键
      },
    );
    return Material(child: willPopScope, color: backgroundColor());
  }

  ///搜索框
  Widget _search(BuildContext context) {
    Widget widget = StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        presenter?.setStateSearch = setState;
        var textField = TextField(
          textAlign: TextAlign.start,
          textAlignVertical: TextAlignVertical.center,
          onChanged: (value) {
            //文本发生变化
            setState(() {
              presenter?.searContent = value;
            });
            presenter?.setStateBody?.call(() {});
          },
          controller: TextUtils.setTextEditingController(text: presenter?.searContent),
          autofocus: true,
          decoration: InputDecoration(
              //尾部删除图标
              suffixIcon: (presenter.searContent!.length > 0)
                  ? Container(
                      width: 40,
                      height: 40,
                      child: InkWell(
                        child: Center(
                          child: Icon(
                            Icons.clear,
                            color: Colors.grey,
                            size: 16,
                          ),
                        ),
                        onTap: () {
                          //文本清除
                          setState(() {
                            presenter.searContent = "";
                          });
                          presenter?.setStateBody?.call(() {});
                        },
                      ),
                    )
                  : null,
              prefixIcon: Icon(Icons.search, color: Colors.black),
              hintText: AppStrings.of(context).search,
              contentPadding: EdgeInsets.symmetric(horizontal: 8, vertical: 8),
              focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                      color: Colors.black, width: 1, style: BorderStyle.solid),
                  borderRadius: BorderRadius.all(Radius.circular(30.0))),
              border: OutlineInputBorder(
                  borderSide: BorderSide(
                      color: Colors.grey, width: 1, style: BorderStyle.solid),
                  borderRadius: BorderRadius.all(Radius.circular(30.0)))),
        );
        return SizedBox(
          child: textField,
          height: 35,
        );
      },
    );
    return Padding(
      padding: EdgeInsets.only(right: 16, top: 0, bottom: 0),
      child: widget,
    );
  }

  //主体布局
  Widget _body(BuildContext context) {
    return StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        presenter?.setStateBody = setState;
        List<YwxItem> allItems = YwxIdManager.getAllItems(context);
        List<YwxItem> searchItems = [];
        allItems.forEach((element) {
          if (StringUtils.isNotEmpty(presenter.searContent)) {
            if (element.YwxName?.contains(presenter.searContent) ?? false) {
              searchItems.add(element);
            }
          }
        });
        if (searchItems.length <= 0) {
          //历史搜索记录
          return getSearchHistoryLayout(context);
        }
        return ListView.builder(
          itemBuilder: (BuildContext context, int index) {
            var item = searchItems[index];
            return Material(
              color: backgroundColor(),
              child: InkWell(
                onTap: () {
                  item.goWorks(context);
                  //添加搜索记录
                  //AppDataCache.addHistoryWithSearch(presenter?.searContent);
                  AppDataCache.addHistoryWithSearch(
                      item.YwxName); //感觉还是存储具体功能名称比较实用。
                },
                child: Container(
                  height: 55,
                  child: ListTile(
                    title: Text(
                      item.YwxName!,
                      style: AppStyle.textStyleWithItem(),
                    ),
                    leading: Image.asset(
                      item.ImagePath!,
                      width: 40,
                      height: 40,
                    ),
                  ),
                ),
              ),
            );
          },
          itemCount: searchItems.length,
        );
      },
    );
  }

  ///获取搜索历史记录
  Widget getSearchHistoryLayout(BuildContext context) {
    List<String>? searchHistories = AppDataCache.getHistoryWithSearch();
    return StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        List<Widget> children = [];
        searchHistories?.forEach((element) {
          Widget child = AppUi.searchChild(context, element, () {
            setState(() {
              //移除历史记录
              AppDataCache.removeHistoryWithSearch(element);
            });
          }, onTapText: () {
            //文本搜索点击事件
            presenter?.searContent = element;
            presenter?.setStateSearch?.call(() {});
            presenter?.setStateBody?.call(() {});
          });
          children.add(child);
        });
        //返回空布局
        if (children.length <= 0) {
          return AppUi.getEmptyView();
        }
        var height = 55.0;
        var row = Row(
          children: [
            Expanded(
                child: SingleChildScrollView(
              padding: EdgeInsets.zero,
              scrollDirection: Axis.horizontal,
              child: Container(
                height: height,
                alignment: Alignment.center,
                child: Row(
                  children: children,
                ),
              ),
            )),
            Container(
              height: height,
              alignment: Alignment.center,
              child: Row(
                children: [
                  Image.asset(
                    ImagePathUtils.getPathWithImage('ic_gradent_line.png'),
                    height: height,
                  ),
                  InkWell(
                    onTap: () {
                      //清空
                      AppDialog.showDialogWithAlert(context,
                              content: AppStrings.of(context).confirmEmpty)
                          ?.then((value) {
                        if (BoolUtils.isBool(value)) {
                          setState(() {
                            AppDataCache.setHistoryWithSearch(null);
                          });
                        }
                      });
                    },
                    child: SizedBox(
                      child: Center(
                        child: Padding(
                          padding: EdgeInsets.only(left: 8, right: 16),
                          child: Text(
                            AppStrings.of(context).empty,
                            style: AppStyle.textStyleWithLittle(),
                          ),
                        ),
                      ),
                      height: height,
                    ),
                  )
                ],
              ),
            )
          ],
        );
        var column = Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "   " + AppStrings.of(context).Historical,
              style: AppStyle.textStyleWithTitle(),
            ),
            row
          ],
        );
        return column;
      },
    );
  }
}

class _Presenter {
  ///body视图状态
  StateSetter? setStateBody;

  ///搜索框视图状态
  StateSetter? setStateSearch;

  //文本搜索内容
  String searContent = "";
}
